package com.jof.framework.jdbc;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jonathan
 *
 */
public class SimpleProfiler implements JdbcProfiler,Runnable {
	private static final Logger LOGGER = LoggerFactory.getLogger(SimpleProfiler.class);
	private boolean enabled = true;
	private ExecutorService executorService = Executors.newFixedThreadPool(2);
	/**
	 * 1000条sql执行一次统计
	 */
	private int cacheSize = 1000;
	private Queue<JdbcLogContext> logQueue = new ConcurrentLinkedQueue<JdbcLogContext>();
	public void setEnabled(boolean enabled){
		this.enabled = enabled;
		startOrRestartThread();
	}
	
	public int getCacheSize() {
		return cacheSize;
	}

	public void setCacheSize(int cacheSize) {
		this.cacheSize = cacheSize;
		if(logQueue != null){
			logQueue.clear();
		}
		startOrRestartThread();
	}

	
	public boolean isEnabled() {
		return this.enabled;
	}

	
	public void log(JdbcLogContext jdbcLogContext) {
		if(!enabled){
			return;
		}
		logQueue.add(jdbcLogContext);
		startOrRestartThread();
	}

	private void startOrRestartThread(){
		if(this.enabled){//重启线程
			executorService.execute(this);
		}
	}
	
	public void run() {
		if(logQueue.size() >= cacheSize){
			for(int i =0;i < logQueue.size(); i++){
				LOGGER.warn("@@@@@@@@@@@@@"+logQueue.poll()+"@@@@@@@@@@@@@");
			}
		}
	}
}
